import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../common/utils.dart';

import '../common/sharedPreferences_helper.dart';

class VideoListController extends GetxController {
  @override
  void onInit() {
    super.onInit();

    _getEyepetizerToken();
  }

  void _getTokenExpires(String data) async {
    final regExp = RegExp(r'expires=([^;]+)');
    final match = regExp.firstMatch(data);
    if (match != null) {
      final dateString = match.group(1) ?? '';

      DateFormat dateFormat = DateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", 'en_US');
      DateTime dateTime = dateFormat.parseUtc(dateString);
      int ts = dateTime.millisecondsSinceEpoch;
      await SharedPreferencesHelper.setInt("eyepetizer_accessToken_expires", ts);
    }
  }

  void _getAccessToken(List<String> cookies) async {
    final regExp = RegExp(r'access_token=([^;]+)');
    for (var s in cookies) {
      final match = regExp.firstMatch(s);
      if (match != null) {
        _getTokenExpires(s);
        final accessToken = match.group(1) ?? '';
        await SharedPreferencesHelper.setString("eyepetizer_accessToken", accessToken);
        break;
      }
    }
  }

  //https://m.eyepetizer.net/u1/video-detail?video_id=326168
  //https://m.eyepetizer.net/
  void _getEyepetizerToken() async {

    String token = SharedPreferencesHelper.getString("eyepetizer_accessToken") ?? '';
    if (!isEmpty(token)) {
      int ts = SharedPreferencesHelper.getInt("eyepetizer_accessToken_expires") ?? 0;
      int currentTS = DateTime.now().millisecondsSinceEpoch;
      if (ts > 0 && currentTS < ts) {
        //token没过期
        return;
      }
    }

    try {
      Dio dio = Dio();
      final url = "https://proxy.eyepetizer.net/v1/card/page/get_nav";
      final data = {
        "tab_label": "mainpage",
        "version": "3.0.14",
      };

      dio.options.headers["x-thefair-appid"] = 'xfpa44crf2p70lk8';
      dio.options.headers["x-thefair-auth"] = '';
      dio.options.headers["x-thefair-cid"] = '';
      dio.options.headers["x-thefair-forward-host"] = 'https://api.eyepetizer.net';
      dio.options.headers["x-thefair-ua"] = 'EYEPETIZER_UNIAPP_H5/100000 (android;android;OS_VERSION_UNKNOWN;zh-Hans-CN;h5;2.0.0;cn-bj;SOURCE_UNKNOWN;PHPSESSID;4096*2304;NETWORK_UNKNOWN) cardsystem/2.0';
      dio.options.headers["content-type"] = 'application/x-www-form-urlencoded';

      final response = await dio.post(
        url,
        data: data,
      );

      final headers = response.headers;
      if (headers['set-cookie'] != null) {
        final cookies = headers['set-cookie'] ?? [];
        _getAccessToken(cookies);
      }
    } catch (e) {
      print(e);
    }
  }
}
